package org.jsola.hr.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.jsola.admin.vo.SiteVO;
import org.jsola.common.DateKit8;
import org.jsola.common.StrKit;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.exception.HrException;
import org.jsola.hr.provider.ISiteProviderService;
import org.jsola.hr.provider.ITokenProviderService;
import org.jsola.hr.provider.IUserProviderService;
import org.jsola.user.constant.UserConstants;
import org.jsola.user.core.UserContext;
import org.jsola.user.entity.UserSiteDO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 租户到期校验拦截器
 *
 * @author wu
 */
@Component
@Slf4j
public class HrSiteExpireInterceptor extends HandlerInterceptorAdapter {
    private Logger logger = LoggerFactory.getLogger(HrSiteExpireInterceptor.class);

    @Autowired
    private ITokenProviderService tokenProviderService;
    @Autowired
    private ISiteProviderService siteProviderService;
    @Autowired
    private IUserProviderService userProviderService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        // 判断用户是否登录
        if (UserContext.getUser() == null) {
//            throw new ParamException("token不能为空");
            // 用户未登录不拦截
            return true;
        }

        String userId = UserContext.getUser().getUserId();
        String siteId = UserContext.getUser().getSiteId();
        // C端用户 不校验站点
        if (UserConstants.DEFAULT_SITE_ID.equals(siteId)) {
            return true;
        }
        SiteVO siteVO = siteProviderService.selectById(siteId, siteId);
        if (siteVO == null) {
            log.error("站点Id有误：{}", siteId);
            throw new HrException("token对应的租户不存在或已删除，请刷新重新登录");
        }
        if (siteVO.getExpireDate() == null) {
            return true;
        }
        // 当天开始时间
        Date dayStart = DateKit8.getStartTime(new Date());
        // 租户到期时间小于当前的开始时间
        if (siteVO.getExpireDate().getTime() < dayStart.getTime()) {
            // 租户已到期，查找该用户的其他租户，找到一个没有过期的租户，然后切换
            List<UserSiteDO> userSiteList = userProviderService.selectByUserId(userId);
            if (CollectionUtils.isEmpty(userSiteList)) {
                throw new HrException("当前登录租户已到期，请联系管理员续期后重试");
            }
            String newSiteId = "";
            for (UserSiteDO userSiteDO : userSiteList) {
                siteVO = siteProviderService.selectById(userSiteDO.getUserSiteId(), userSiteDO.getUserSiteId());
                if (Objects.isNull(siteVO)) {
                    continue;
                }
                if (siteVO.getExpireDate() == null || siteVO.getExpireDate().getTime() > System.currentTimeMillis()) {
                    newSiteId = siteVO.getId();
                    break;
                }
            }
            if (StrKit.isEmpty(newSiteId)) {
                throw new HrException("当前登录租户已到期，请联系管理员续期后重试");
            }
            // 切换租户
//            JwtTokenDTO jwtTokenDTO = tokenProviderService.switchToken(tokenStr, newSiteId);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            try {
                Result<String> result = new Result<>();
                result.setCode(101);
                result.setSuccess(false);
                result.setMsg("租户过期，存在没过期的租户，请切换租户");
                result.setData(newSiteId);
                PrintWriter out = response.getWriter();
                out.append(result.toString());
                return false;
            } catch (Exception e) {
                e.getMessage();
                throw new ParamException("切换租户失败!");
            }
        }
        return true;
    }

}
